package strategies;

//~--- non-JDK imports --------------------------------------------------------

import client.JForexMain;

import com.dukascopy.api.system.*;

import org.slf4j.Logger;

//~--- JDK imports ------------------------------------------------------------

import java.awt.*;

import java.io.File;
import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Calendar;

/**
 *
 * @author brian
 */
public class MySystemListener implements ISystemListener {
    private String                  jnlpUrl         = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
    private int                     lightReconnects = 3;
    private String                  password        = "";
    private String                  userName        = "";
    private Calendar                start           = Calendar.getInstance();
    private String                  fileName;
    private Logger                  logger;
    private ArrayList<StrategyArgs> sargs;
    private boolean                 started;
    private Strategy                strategy;
    private ITesterClient           testClient;

    public MySystemListener(Logger logger, ITesterClient client, String userName, String password, String fileName,
                            ArrayList<StrategyArgs> args, Strategy strategy) {
        this.logger     = logger;
        this.testClient = client;
        this.userName   = userName;
        this.password   = password;
        this.fileName   = fileName;
        this.started    = true;
        this.sargs      = args;
        this.strategy   = strategy;
    }

    /**
     * Called on new strategy start
     *
     * @param processId
     *            id of the started strategy
     */
    @Override
    public void onStart(long processId) {
        logger.info("Strategy started: " + processId);
        started = true;
        start   = Calendar.getInstance();
    }

    /**
     * Called on the strategy stop
     *
     * @param processId
     *            id of the strategy stopped
     */
    @Override
    public void onStop(long processId) {
        logger.info("Strategy stopped: " + processId);

        if (testClient.getStartedStrategies().size() == 0) {
            logger.info("No further strategies remaining; exiting");

            try {
                SimpleDateFormat dateFormat         = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
                String           fileNameWithoutExt = "Report_" + strategy.getName() + "_"
                                                      + dateFormat.format(Calendar.getInstance().getTime()) + fileName;
                File f = new File(fileNameWithoutExt + ".html");

                Strategy.reportFileName = fileNameWithoutExt + ".csv";
                testClient.createReport(processId, f);
                Desktop.getDesktop().open(f);
                started = false;

                String file = JForexMain.strategy.writeOrders(fileNameWithoutExt + ".csv");

                if (JForexMain.strategy instanceof DummyStrategy) {
                    ((DummyStrategy) JForexMain.strategy).flushBuffers();
                }

                // Desktop.getDesktop().open(new File(file));
                // JOptionPane.showMessageDialog(null, (Calendar.getInstance()
                // .getTimeInMillis() - start.getTimeInMillis()) / 1000);
                System.out.println("Strategy Run completed " + Calendar.getInstance().getTime());

                if (sargs.size() > 0) {
                    StrategyArgs arg = sargs.get(0);

                    JForexMain.strategy = new AdaptiveTakeProfitStrategy(arg);
                    sargs.remove(0);
                    JForexMain.runStrategy(JForexMain.strategy);
                } else {
                    System.exit(0);
                }
            } catch (IllegalStateException e) {

                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {

                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Called on successfull connect
     */
    @Override
    public void onConnect() {
        logger.info("Connected");
        lightReconnects = 3;
    }

    /**
     * Called on disconnect
     */
    @Override
    public void onDisconnect() {
        logger.warn("Disconnected");

        if (lightReconnects > 0) {
            testClient.reconnect();
            --lightReconnects;
        } else {
            try {

                // sleep for 10 seconds before attempting to reconnect
                Thread.sleep(10000);
            } catch (InterruptedException e) {

                // ignore
            }

            try {
                testClient.connect(jnlpUrl, userName, password);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    public boolean isRunning() {
        return started;
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
